<template>
  <van-icon
    @click="onCollect"
    :loading="loading"
    :class="{ collected: value === 1 }"
    :name="value === 1 ? 'good-job' : 'good-job-o'"
  />
</template>

<script>
import { addLike, deleteLike } from "@/api/article";

export default {
  name: "LikeArticle",
  props: {
    value: {
      type: Number,
      required: true,
    },
    artId: {
      type: [Number, Object, String],
      required: true,
    },
  },
  data() {
    return {
      loading: false,
    };
  },
  methods: {
    async onCollect() {
      this.loading = true;
      try {
        let attitude = -1;
        if (this.value === 1) {
          // 取消点赞
          await deleteLike(this.artId);
        } else {
          // 点赞
          await addLike(this.artId);
          attitude = 1;
        }
        // 更新视图
        this.$emit("input", attitude);
        this.$toast.success(this.value === 1 ? "点赞成功" : "点赞失败");
      } catch (err) {
        this.$toast.fail("操作失败，请重试");
      }
      this.loading = false;
    },
  },
};
</script>

<style scoped lang="less">
.collected {
  color: #e5645f;
}
</style>
